package com.platform.cdcs.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.client.android.CaptureActivityHandler;
import com.google.zxing.client.android.CaptureInterface;
import com.google.zxing.client.android.DecoderMode;
import com.google.zxing.client.android.FinishListener;
import com.google.zxing.client.android.InactivityTimer;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.ViewfinderView;
import com.google.zxing.client.android.camera.CameraManager;
import com.platform.cdcs.R;
import com.platform.cdcs.tool.Constant;
import com.trueway.app.uilib.activity.BaseActivity;
import com.trueway.app.uilib.tool.Utils;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * Created by holytang on 2017/11/15.
 */
public class ScanBaseActivity extends BaseActivity implements SurfaceHolder.Callback, CaptureInterface {
    private static final String TAG = ScanBaseActivity.class.getSimpleName();
    public boolean pdaFlag = false;
    protected ViewfinderView viewfinderView;
    SurfaceView surfaceView;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private boolean hasSurface;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    private Collection<BarcodeFormat> decodeFormats;
    private Result savedResultToShow;
    private InactivityTimer inactivityTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, Constant.PERMISSION_CAMERA);
            }
        }
    }

    protected void modeInit() {

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            // Creating the handler starts the preview, which can also throw a RuntimeException.
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
                modeInit();
            }
            decodeOrStoreSavedBitmap(null, null);
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.?lang.?RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    private void displayFrameworkBugMessageAndExit() {
        Utils.showToast(getContext(), "很遗憾，Android 相机出现问题。你可能需要重启设备。");
    }

    private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
        // Bitmap isn't used yet -- will be used soon
        if (handler == null) {
            savedResultToShow = result;
        } else {
            if (result != null) {
                savedResultToShow = result;
            }
            if (savedResultToShow != null) {
                Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
                handler.sendMessage(message);
            }
            savedResultToShow = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
        }
//        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
//        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    @Override
    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    protected void onScanQRCodeSuccess(String result) {

    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }

    @Override
    public void handleDecode(String result) {
        onScanQRCodeSuccess(result);
    }

    @Override
    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    @Override
    protected void initLayout() {

    }

    @Override
    protected void initView() {
        hasSurface = false;
        inactivityTimer = new InactivityTimer(getActivity());
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (pdaFlag) {
            return;
        }
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        handler = null;

        resetStatusView();
        inactivityTimer.onResume();

        decodeFormats = null;
        characterSet = null;

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        surfaceView.setVisibility(View.VISIBLE);
//        if (hasSurface) {
//            // The activity was paused but not stopped, so the surface still exists. Therefore
//            // surfaceCreated() won't be called, so init the camera here.
//            initCamera(surfaceHolder);
//        } else {
            // Install the callback and wait for surfaceCreated() to init the camera.
            surfaceHolder.addCallback(this);
//        }
    }


    public void resumt(){
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        handler = null;

        resetStatusView();
        inactivityTimer.onResume();

        decodeFormats = null;
        characterSet = null;

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        surfaceView.setVisibility(View.VISIBLE);
//        if (hasSurface) {
//            // The activity was paused but not stopped, so the surface still exists. Therefore
//            // surfaceCreated() won't be called, so init the camera here.
//            initCamera(surfaceHolder);
//        } else {
        // Install the callback and wait for surfaceCreated() to init the camera.
        surfaceHolder.addCallback(this);
        initCamera(surfaceHolder);
//        }
    }
    public void openCamera() {
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);
        handler = null;

        resetStatusView();
        inactivityTimer.onResume();

        decodeFormats = null;
        characterSet = null;

        surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        surfaceView.setVisibility(View.VISIBLE);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
//        surfaceView.setVisibility(View.VISIBLE);
//        if (hasSurface) {
//            // The activity was paused but not stopped, so the surface still exists. Therefore
//            // surfaceCreated() won't be called, so init the camera here.
//            initCamera(surfaceHolder);
//        } else {
            // Install the callback and wait for surfaceCreated() to init the camera.
        surfaceHolder.addCallback(this);
//        }
    }

    public void closeCamera() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        cameraManager.closeDriver();
//        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
            surfaceView.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (pdaFlag) {
            return;
        }
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        cameraManager.closeDriver();
        //historyManager = null; // Keep for onActivityResult
//        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
            surfaceView.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onDestroy() {
        if (inactivityTimer != null) {
            inactivityTimer.shutdown();
        }
        super.onDestroy();
    }


    public void startSpot() {
        restartPreviewAfterDelay(1000L);
    }

    public void changeScanMode(DecoderMode mode) {
        if (handler != null) {
            handler.setMode(mode);
        }
    }
}
